package com.wan.fragment


import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.content.LocalBroadcastManager
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import com.wan.R
import com.wan.activity.WebActivity
import com.wan.adapter.HomeRvAdapter
import com.wan.base.BaseBean
import com.wan.entity.HomeArtEntity
import com.wan.entity.HomeArtItemEntity
import com.wan.receiver.ResultRefreshDataReceiver
import com.wan.receiver.SearchChangeTextReceiver
import com.wan.uitls.*
import kotlinx.android.synthetic.main.fragment_search_result.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


/**
 * search result
 * 关于数据的刷新应该使用 广播
 */
class SearchResultFragment : Fragment(), ResultRefreshDataListener, ItemRightViewListener, ItemClickListener, QueryTextChangeListener {


    private val mThreadName = this.javaClass.name


    private lateinit var adapter: HomeRvAdapter
    private var dataList = ArrayList<HomeArtItemEntity>()

    private var currentPage: Int = 0

    private var searchText: String? = null

    //从展示界面过来的单词
    private lateinit var refreshDataReceiver: ResultRefreshDataReceiver

    //从activity 中searchView 过来的单词
    private lateinit var queryTextReceiver: SearchChangeTextReceiver

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_search_result, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
    }

    private fun initData() {
        result_content_rv.layoutManager = LinearLayoutManager(context)
        adapter = HomeRvAdapter(context!!, dataList, R.layout.fragment_home_item_layout)
        adapter.setItemClickListener(this)
        result_content_rv.adapter = adapter


        refreshDataReceiver = ResultRefreshDataReceiver(this)
        var filter = IntentFilter()
        filter.addAction(CommonUtils.Action_Result_Fragment_Refresh)
        LocalBroadcastManager.getInstance(context!!).registerReceiver(refreshDataReceiver, filter)


        queryTextReceiver = SearchChangeTextReceiver(this)
        var queryFilter = IntentFilter()
        queryFilter.addAction(CommonUtils.Action_Search_Change_Text)
        LocalBroadcastManager.getInstance(context!!).registerReceiver(queryTextReceiver, queryFilter)

    }

    private fun requestData(text: String, page: Int) {
        var apiManager = ApiManager(this)
        apiManager.postSearchArticle(page, text).enqueue(object : Callback<BaseBean<HomeArtEntity>> {
            override fun onFailure(call: Call<BaseBean<HomeArtEntity>>, t: Throwable) {
                Log.d(mThreadName, " onFailure : search 失败了 ==> ${call.execute().body()}")
            }

            override fun onResponse(call: Call<BaseBean<HomeArtEntity>>, response: Response<BaseBean<HomeArtEntity>>) {
                Log.d(mThreadName, "onResponse : search 成功了 ==> ${response.body()}")
                var homeArtEntity = response.body()!!.data
                var arrayList = homeArtEntity.datas
                if (arrayList.isNotEmpty()) {
                    dataList.addAll(arrayList)
                    adapter.notifyDataSetChanged()
                }
            }
        })
    }


    override fun onRightViewClickListener(position: Int) {
        CommonUtils.toastWord(context!!, "right pic view click")

    }

    override fun onQueryTextChangeListener(intent: Intent) {
        var text = intent.getStringExtra(CommonUtils.Search_Change_Text)
        if (searchText == text) {
            return
        }
        searchText = text
        currentPage = 0
        requestData(text, currentPage)
    }

    override fun onResultRefreshDataListener(intent: Intent) {
        var text = intent.getStringExtra(CommonUtils.Search_Text)
        if (searchText == text) {
            return
        }
        searchText = text
        currentPage = 0
        requestData(text, currentPage)

    }

    override fun onItemClickListener(position: Int) {
        CommonUtils.sendIntent(context!!, WebActivity::class.java, dataList[position].link, dataList[position].title)
    }

    override fun onDestroy() {
        super.onDestroy()
        LocalBroadcastManager.getInstance(context!!).unregisterReceiver(refreshDataReceiver)
        LocalBroadcastManager.getInstance(context!!).unregisterReceiver(queryTextReceiver)
        RetrofitHelper.get().cancelCall(this)
    }


}
